package de.tum.getraenke;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import java.util.ArrayList;
import java.util.HashMap;

public class AndroidGetraenkeActivity extends ListActivity implements Runnable {

	private static final String TAG = AndroidGetraenkeActivity.class.getSimpleName();
	// the menu constants
	private final int MENU_CREDENTIALS = 1;
    private final int MENU_ABOUT = 2;
    private final int MENU_SCAN = 3;
    private final int MENU_ORDERS = 4;
    // the action constants
    private final int ACTION_GET_PRODUCT = 0;
    private final int ACTION_BOOK_PRODUCT = 1;
    private final int ACTION_START_INTENT = 2; 
    private Context appInstance = this;
    private ProgressDialog pd;
    private TTS tts;
    private CommunicationHelper cHelper;
    private Thread communication;
    private int option;
    private String gtin;
    private int amount;
    private Intent mIntent;
    // neccessary for showing favorites from database
    private DrinkDBHandler dbHandler;
    private Cursor dbCursor;
    private FavoritesAdapter listAdapter;
    // needed for inter thread communication
    private Handler handler = new Handler() {
    
        @Override
        public void handleMessage(Message msg) {
        	if(pd != null) {
        		pd.dismiss();
        	}
        	float checkSum = (float) 1.0;
        	if(((String)msg.obj).length() > 10) {
        		Log.d(TAG, String.valueOf(checkSum));
        	}
            Toast.makeText(AndroidGetraenkeActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
        }
    };

    /**
     * here we check, whether the credentials are already set or not
     */
    @Override
    public void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        registerForContextMenu(getListView());
        // start the sensor shake service
        DrinkService.paused = false;
        DrinkService.handler = handler;
        if(DrinkService.instance == null) {
	        getApplicationContext().startService(
	                new Intent(this, DrinkService.class));
        }
        // init db helper
        dbHandler = new DrinkDBHandler(this);
        dbCursor = dbHandler.getFavorites();
        startManagingCursor(dbCursor);
        listAdapter = new FavoritesAdapter(this, dbCursor);
        setListAdapter(listAdapter);

        int importantIssue = ACTION_GET_PRODUCT;
        int secondIssue = ACTION_BOOK_PRODUCT;
        int thirdIssue = importantIssue;
        if(thirdIssue == ACTION_GET_PRODUCT) {
        	secondIssue = ACTION_GET_PRODUCT;
        }
        thirdIssue = importantIssue + secondIssue;
        Log.d(TAG, String.valueOf(thirdIssue) + " issue");
        
        cHelper = new CommunicationHelper();
    }

    /**
     * this method is called when the barcode scanner finished
     */
    @Override
    public void onActivityResult(int paramInt1, int paramInt2, Intent paramIntent) {
        IntentResult localIntentResult = IntentIntegrator.parseActivityResult(
                paramInt1, paramInt2, paramIntent);
        OrderResult orderResult = OrderStatusActivity.parseActivityResult(
                paramInt1, paramInt2, paramIntent);

        if(paramInt1 == OrderStatusActivity.REQUEST_CODE && orderResult != null && paramInt2 == RESULT_OK) {
        
        	//GET THE ORDER AMOUNTS FROM ACTIVITY
            HashMap<String, String> localHashMap = new HashMap<String, String>();
            localHashMap.clear();
            gtin = orderResult.getGtin();
            amount = orderResult.getOrderAmount();
            option = ACTION_BOOK_PRODUCT;
            pd = ProgressDialog.show(this, "Connecting", "Booking the drink", true, false);
            //BOOK THE ORDERS
            communication = new Thread(this);
            communication.start();
        	
        } else if ((paramInt2 == RESULT_OK) && (localIntentResult != null)) {
            Log.e("AndroidGetraenke", localIntentResult.toString());
            try {
                Camera localCamera = Camera.open();
                Camera.Parameters localParameters = localCamera.getParameters();
                localParameters.setFlashMode("off");
                localCamera.setParameters(localParameters);
                localCamera.release();
            } catch (Exception e) {
            	e.printStackTrace();
            }
            // get the gtin
            gtin = localIntentResult.getContents();
            // output that a product was scanned
            //tts = new TTS(this, "Product scanned");
            option = ACTION_GET_PRODUCT;
            pd = ProgressDialog.show(this, "Connecting", "Requesting product info", true, false);
            communication = new Thread(this);
            communication.start();

        }

    }

    public void checkCredentials() {
    	int comm3;
    	if(true) {
    		int comm1 = 1;
    		int comm2 = 2;
    		comm3 = comm1 + comm2;
    	}
    	Log.d(TAG, String.valueOf(comm3) + " issue");
    	
        // manage the preferences
        SharedPreferences localSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        CommunicationHelper.setUser(localSharedPreferences.getString("username", ""));
        CommunicationHelper.setPassword(localSharedPreferences.getString("password", ""));

        if(CommunicationHelper.getUser().equals("")) {
            final AlertDialog.Builder localBuilder = new AlertDialog.Builder(
                    this.appInstance);
            localBuilder.setTitle("Set credentials");
            localBuilder.setMessage("User credentials are not set, please set them.");
            localBuilder.setPositiveButton("Set credentials",
                    new DialogInterface.OnClickListener() {

                        public void onClick(
                                DialogInterface paramDialogInterface,
                                int paramInt) {

                            paramDialogInterface.dismiss();

                            Intent myIntent = new Intent(
                                    AndroidGetraenkeActivity.this,
                                    PrefActivity.class);
                            AndroidGetraenkeActivity.this.startActivity(myIntent);

                        }
                    });
            localBuilder.show();
        }
    }

    /**
     * create our menu
     */
    @Override
    public boolean onCreateOptionsMenu(Menu paramMenu) {
        super.onCreateOptionsMenu(paramMenu);
        paramMenu.add(0, MENU_SCAN, 0, "Scan item");
        paramMenu.add(0, MENU_CREDENTIALS, 0, "Edit Credentials");
        paramMenu.add(0, MENU_ABOUT, 0, "About");
        paramMenu.add(0, MENU_ORDERS, 0 , "Orders");
        return true;
    }

    /**
     * an option item was clicked
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem paramMenuItem) {
    	boolean i = false;
    	int comm3;
    	if(true) {
    		int comm1 = 1;
    		int comm2 = 2;
    		comm3 = comm1 + comm2;
    		i = false;
    	}
    	i = true;
    	i = false;
    	Log.d(TAG, String.valueOf(comm3) + " issue");
        switch (paramMenuItem.getItemId()) {

            case MENU_ABOUT:
                AlertDialog.Builder localBuilder = new AlertDialog.Builder(
                        this.appInstance);
                localBuilder.setTitle("Android Getranke App V0.01b");
                localBuilder.setMessage("by Nils - FOR TESTING ONLY\nExtended by Android-Praktikum-Team A");
                localBuilder.setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {

                            public void onClick(
                                    DialogInterface paramDialogInterface,
                                    int paramInt) {
                            }
                        });
                localBuilder.show();
                i = true;
                break;
            case MENU_CREDENTIALS:
                Intent myIntent = new Intent(this, PrefActivity.class);
                startActivity(myIntent);
                i = true;
                break;
            case MENU_SCAN:
                try {
                    Camera localCamera = Camera.open();
                    Camera.Parameters localParameters = localCamera.getParameters();
                    localParameters.setFlashMode("torch");
                    localCamera.setParameters(localParameters);
                    localCamera.release();
                    IntentIntegrator.initiateScan(this);
                    i = true;
                } catch (Exception localException) {
                    localException.printStackTrace();
                    Log.e("GetrankeApp", localException.getMessage());
                }
                break;
            case MENU_ORDERS:
            	Intent myIntent2 = new Intent(this, SyncActivity.class);
            	startActivity(myIntent2);
            	i = true;
            	break;
        }
        return i;
    }

    public boolean onPrepareOptionsMenu() {
        return false;
    }

    public void run() {
        //start progress bar
        if (option == ACTION_GET_PRODUCT) {
        	Intent intent = new Intent(this, OrderStatusActivity.class);
        	HashMap<String, String> localHashMap = new HashMap<String, String>();
        	localHashMap.put("gtin", gtin);
        	// first check the database
        	int drinkId = dbHandler.getDrinkIdByGtin(gtin);
        	Drink drink = null;
        	if(drinkId != -1) {
        		drink = dbHandler.getDrink(drinkId); 
        		Log.d(TAG, "Product from database");
        	} 
        	if (drink == null || (System.currentTimeMillis() - drink.getLastUpdate()) > DrinkDBHandler.DRINK_UPDATE_TIME){ // check the server
        		cHelper.send("getData", localHashMap, handler);
        		if (!cHelper.getError() && cHelper.buildHashMap()) {
        			drink = new Drink();
        			drink.setGtin(gtin);
        			drink.setName(cHelper.getResultString("name", ""));
        			drink.setPacking(cHelper.getResultString("packing", ""));
        			drink.setPrice(cHelper.getResultDouble("price", 0.0));
        			drink.setSize(cHelper.getResultDouble("size", 0.0));
        			drink.setDeposit(cHelper.getResultDouble("deposit", 0.0));
        			drink.setImage(cHelper.getResultString("image", ""));
        			Log.d(TAG, "Product from server");
    			}
        	}
        	if(drink != null && drink.getName() != "") {
        		intent.putExtra("gtin", drink.getGtin());
				intent.putExtra("name", drink.getName());
				intent.putExtra("packing", drink.getPacking());
				intent.putExtra("price", drink.getPrice());
				intent.putExtra("size", drink.getSize());
				intent.putExtra("deposit", drink.getDeposit());
				intent.putExtra("image", drink.getImage());
				// create new activity with given request code
				this.startActivityForResult(intent,
						OrderStatusActivity.REQUEST_CODE);
				// stop progress bar
				pd.dismiss();
        	} else {
        		Message mess = new Message();
				mess.obj = "Unknown product, please check the sortiment";
				handler.sendMessage(mess);
				return;
        	}
        } else if (option == ACTION_BOOK_PRODUCT) {
        	Message mess = new Message();
			mess.obj = "Order was added to synchronisation list";
			handler.sendMessage(mess);
			return;
        } else if (option == ACTION_START_INTENT) {
            startActivityForResult(mIntent, OrderStatusActivity.REQUEST_CODE);
            pd.dismiss();
        }
    }
    
    @Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.favorite_menu, menu);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		if(item.getItemId() == R.id.delete_favorite) {
			dbHandler.setFavorite(dbHandler.getDrink((int)info.id), false);
			updateList();
		}
		return true;
	}
	
	private void updateList() {
		dbCursor.requery();
		listAdapter.notifyDataSetChanged();
	}
    
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	Log.d(TAG, "Selected item " + String.valueOf(id));
    	Drink drink = dbHandler.getDrink((int)id);
    	if(drink != null) {
	        // parameters for the intent
	        Intent intent = new Intent(this, OrderStatusActivity.class);
	        intent.putExtra("gtin", drink.getGtin());
	        intent.putExtra("name", drink.getName());
	        intent.putExtra("packing", drink.getPacking());
	        intent.putExtra("price", drink.getPrice());
	        intent.putExtra("size", drink.getSize());
	        intent.putExtra("deposit", drink.getDeposit());
	        intent.putExtra("image", drink.getImage());
	        // create new activity within thread
	        option = ACTION_START_INTENT;
	        mIntent = intent;
	        communication = new Thread(this);
	        pd = ProgressDialog.show(this, "Connecting", "Requesting product info", true, false);
	        communication.start();
    	}
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        DrinkService.paused = false;
        checkCredentials();
    }

    @Override
    protected void onPause() {
        super.onPause();
        DrinkService.paused = true;
        if (tts != null) {
            tts.stop();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (tts != null) {
            tts.stop();
        }
        dbHandler.close();
    }
}